<template>
    <div class="menu">
        <div v-for="funcGroup in applicationInfo.ChildGroup" :key="funcGroup.ID" class="menu-item">
            <!-- 一级菜单 -->
            <div class="menu-item__header" @click="toggleMenuItem(funcGroup.ID)">
                <div class="menu-item__icon">
                    <i class="icon-t-AP menu-itemHeader__icon"></i>
                </div>
                <span class="menu-item__title">{{ funcGroup.Name }}</span>
                <div class="menu-item__arrow" :class="{ 'menu-item__arrow--expanded': funcGroup.expanded }">
                    <i v-html="MENU_ARROW_UP_ICON"></i>
                </div>
            </div>

            <!-- 二级菜单 -->
            <transition name="menu-slide" @enter="onEnter" @after-enter="onAfterEnter" @leave="onLeave"
                @after-leave="onAfterLeave">
                <div v-show="funcGroup.expanded" class="menu-item__children">
                    <div v-for="func in funcGroup.Functions" :key="func.ID" :id="func.ID" class="menu-item__child"
                        :class="{ 'menu-item__child--active': func.ID == route.query.fid }">
                        <span @click="selectMenuItem(func)">{{ func.Name }}</span>
                        <Popover position="rightTop" trigger="click" ref="popoverRefs" customClass="func-info-popover" @after-enter="(event) => afterEnter(event, func.ID)" @after-leave="afterLeave">
                            <template v-slot:reference>
                                <i v-html="MENU_INFO_MOVE_ICON" :id="func.ID + '_more'" class="menu-move_icon"></i>
                            </template>
                            <FuncInfoTag :funcId="func.ID" :funcName="func.Name" @close-popover="handleClosePopover(func.ID)" />
                        </Popover>
                    </div>
                </div>
            </transition>
        </div>
    </div>
</template>

<script setup>
import { useRoute } from 'vue-router'
import { reactive, ref } from 'vue'
import FuncInfoTag from '@/components/pc/FuncInfoTag.vue'

import { MENU_ARROW_UP_ICON, MENU_INFO_MOVE_ICON } from '@/constants/svg.js'
import Popover from '@/components/common/Popover.vue'

const route = useRoute()

const emit = defineEmits(['menu-select'])


const props = defineProps({
    applicationInfo: {
        type: Object,
        default: () => {
            ChildGroup: []
        }
    }
})

const toggleMenuItem = (id) => {
    if (!props.applicationInfo?.ChildGroup) return

    const item = props.applicationInfo.ChildGroup.find(item => item.ID === id)
    if (item) {
        item.expanded = !item.expanded
    }
}


const selectMenuItem = (selectedFunc) => {
    if (!props.applicationInfo?.ChildGroup) return

    emit('menu-select', selectedFunc)
}


const onEnter = (el) => {
    // 确保元素有固定的宽度，防止在父容器变化时重排
    el.style.width = '100%'
    el.style.minWidth = '200px'

    const realHeight = el.scrollHeight
    el.style.height = '0'
    el.style.opacity = '0'
    el.style.overflow = 'hidden'

    // 强制重绘
    el.offsetHeight

    // 使用requestAnimationFrame确保动画流畅
    requestAnimationFrame(() => {
        el.style.height = realHeight + 'px'
        el.style.opacity = '1'
    })
}

const onAfterEnter = (el) => {
    el.style.height = ''
    el.style.opacity = ''
    el.style.overflow = ''
    el.style.width = ''
    el.style.minWidth = ''
}

const onLeave = (el) => {
    // 固定宽度防止晃动
    el.style.width = '100%'
    el.style.minWidth = '200px'

    el.style.height = el.scrollHeight + 'px'
    el.style.opacity = '1'
    el.style.overflow = 'hidden'

    el.offsetHeight

    requestAnimationFrame(() => {
        el.style.height = '0'
        el.style.opacity = '0'
    })
}

const onAfterLeave = (el) => {
    el.style.height = ''
    el.style.opacity = ''
    el.style.overflow = ''
    el.style.width = ''
    el.style.minWidth = ''
}

const popoverRefs = ref([])


const closeAllPopovers = () => {
  popoverRefs.value.forEach(popover => {
    if (popover && popover.closePopover) {
      popover.closePopover()
    }
  })
}

const afterEnter = (event, funcId) => {
  // 通过 funcId 找到对应的 popover 元素
  const popoverBody = document.querySelector(`.func-info-popover`)
  if (!popoverBody) return
  
  // 找到对应的 popover 引用
  const popoverIndex = props.applicationInfo.ChildGroup
    .flatMap(group => group.Functions || [])
    .findIndex(func => func.ID === funcId)
  
  if (popoverIndex === -1) return
  
  const handleMouseLeave = () => {
    setTimeout(() => {
      if (!popoverBody.matches(':hover')) {
        // 只关闭当前的Popover
        const currentPopover = popoverRefs.value[popoverIndex]
        if (currentPopover && currentPopover.closePopover) {
          currentPopover.closePopover()
        }
      }
    }, 100)
  }
  
  popoverBody.addEventListener('mouseleave', handleMouseLeave)
  // 存储事件处理器以便后续移除
  popoverBody._mouseLeaveHandler = handleMouseLeave
  popoverBody._funcId = funcId // 存储 funcId 用于后续清理
}

const afterLeave = () => {
  // Popover关闭后，移除事件监听器
  const popoverBody = document.querySelector('.func-info-popover')
  if (popoverBody && popoverBody._mouseLeaveHandler) {
    popoverBody.removeEventListener('mouseleave', popoverBody._mouseLeaveHandler)
    delete popoverBody._mouseLeaveHandler
    delete popoverBody._funcId
  }
}

const handleClosePopover = (funcId) => {
  // 找到对应的 popover 引用索引
  const popoverIndex = props.applicationInfo.ChildGroup
    .flatMap(group => group.Functions || [])
    .findIndex(func => func.ID === funcId)
  
  if (popoverIndex !== -1) {
    const currentPopover = popoverRefs.value[popoverIndex]
    if (currentPopover && currentPopover.closePopover) {
      currentPopover.closePopover()
    }
  }
}

defineExpose({
  closeAllPopovers
})
</script>

<style lang="scss">
.menu-item__child {
    .custom-popover-reference {
        height: 32px;
        display: flex;
    }
}
.custom-popover-body.func-info-popover{
    padding: 0;
}
</style>
<style scoped lang="scss">
.menu-move_icon {
    display: none;
    /* 默认隐藏图标 */
    width: 14px;
    height: 14px;
}

.menu-itemHeader__icon {
    display: inline-block;
    text-align: center;
    width: 16px;
    line-height: 1;
    padding: 0;
    flex-shrink: 0;
    margin: 0 8px 0 12px;
    font-size: 14px;
}

.menu {
    width: 100%;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
    position: relative;
    transform: translateZ(0);
}

.menu-item__children {
    padding-left: 12px;
    display: flex;
    flex-wrap: wrap;
    /* 关键优化：防止布局晃动 */
    transform-origin: top;
    backface-visibility: hidden;
    will-change: height, opacity;
    /* 确保容器稳定 */
    box-sizing: border-box;
}

.menu-slide-enter-active {
    transition: height 0.25s cubic-bezier(0.25, 0.8, 0.25, 1),
        opacity 0.25s cubic-bezier(0.25, 0.8, 0.25, 1);
}

.menu-slide-leave-active {
    transition: height 0.2s cubic-bezier(0.4, 0, 0.2, 1),
        opacity 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}

.menu-item {
    margin-bottom: 8px;
    margin-right: 2px;
}

.menu-item__header {
    display: flex;
    align-items: center;
    cursor: pointer;
    transition: all 0.2s ease;
    font-weight: 500;
    padding-left: 8px;
    color: rgb(0, 0, 0);
    height: 38px;
    line-height: 38px;
}

.menu-item__header:hover {
    color: var(--theme-color);
}

.menu-item__icon {
    width: 20px;
    height: 20px;
    margin-right: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.menu-item__icon .icon {
    width: 16px;
    height: 16px;
    color: #666;
}

.menu-item__title {
    flex: 1;
    font-size: 14px;
}

.menu-item__arrow {
    width: 16px;
    height: 16px;
    position: absolute;
    left: 216px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #bcbdc0;
    transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.menu-item__arrow .icon {
    width: 12px;
    height: 12px;
    color: #999;
}

.menu-item__arrow--expanded {
    transform: rotate(180deg);
}

.menu-item__children {
    padding-left: 12px;
    display: flex;
    flex-wrap: wrap;
    /* 添加以下样式来减少晃动 */
    transform-origin: top;
    backface-visibility: hidden;
    will-change: height, opacity;
}

.menu-slide-enter-active {
    transition: height 0.3s cubic-bezier(0.25, 0.8, 0.25, 1),
        opacity 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
}

.menu-slide-leave-active {
    transition: height 0.25s cubic-bezier(0.4, 0, 0.2, 1),
        opacity 0.25s cubic-bezier(0.4, 0, 0.2, 1);
}

.menu-item__child {
    cursor: pointer;
    transition: all 0.2s ease;
    height: 32px;
    line-height: 32px;
    margin-top: 2px;
    font-size: 14px;
    border-right: none;
    width: 105px;
    user-select: none;
    color: #565960;
    display: flex;
    position: relative;
    /* 确保相对定位，便于图标定位 */

    /* 当hover时显示图标 */
    &:hover .menu-move_icon {
        display: block;
    }

    .custom-popover-reference--visible {
        .menu-move_icon {
            display: block;
        }
    }
}

.menu-item__child:hover {
    color: var(--theme-color);
}

.menu-item__child--active {
    color: var(--theme-color);
}

.menu-slide-enter-active {
    transition: all 0.4s cubic-bezier(0.25, 0.8, 0.25, 1);
}

.menu-slide-leave-active {
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
</style>